#!/usr/bin/env node

const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");

const args = process.argv.slice(2);

if (args.length < 2) {
    console.log("用法: node update-expansion-version.js <扩展包ID> <新版本号>");
    console.log(
        "示例: node update-expansion-version.js sdat-creator-tools 1.1.0"
    );
    process.exit(1);
}

const [packId, newVersion] = args;

// 验证版本格式
if (!/^\d+\.\d+\.\d+$/.test(newVersion)) {
    console.error("错误: 版本必须为 X.Y.Z 格式（例如，1.2.3）");
    process.exit(1);
}

async function updateVersion() {
    try {
        // 更新 config.yaml 中的版本
        const configPath = path.join(
            __dirname,
            "..",
            "expansion-packs",
            packId,
            "config.yaml"
        );

        if (!fs.existsSync(configPath)) {
            console.error(`错误: 未找到扩展包 '${packId}'`);
            process.exit(1);
        }

        const configContent = fs.readFileSync(configPath, "utf8");
        const config = yaml.load(configContent);
        const oldVersion = config.version || "unknown";

        config.version = newVersion;

        const updatedYaml = yaml.dump(config, { indent: 2 });
        fs.writeFileSync(configPath, updatedYaml);

        console.log(
            `✓ 已更新 ${packId}/config.yaml: ${oldVersion} → ${newVersion}`
        );
        console.log(`\n✓ 已成功将 ${packId} 更新至版本 ${newVersion}`);
        console.log("\n下一步操作:");
        console.log("1. 测试更改");
        console.log(
            '2. 提交: git add -A && git commit -m "chore: bump ' +
                packId +
                " to v" +
                newVersion +
                '"'
        );
    } catch (error) {
        console.error("更新版本时出错:", error.message);
        process.exit(1);
    }
}

updateVersion();
